package com.kjc.demo.basic.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Component
public class ApiInterceptor implements HandlerInterceptor {

    private static final String LOG_INTERVAL_S_JSON_FORMAT = "==> {\"uri\":\"{}\", \"begin_time\":\"{}\"}";
    private static final String LOG_INTERVAL_E_JSON_FORMAT = "<== {\"uri\":\"{}\", \"end_time\":\"{}\", \"interval\":\"{}\"}";
    private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("SSP-ThreadLocal-StartTime");


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o){
    	log.info("拦截器-----------------------");
        start(request);

        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        end(httpServletRequest);
    }

    private void start(HttpServletRequest request){
        //网关生成的id
        String gwTraceId = request.getHeader("X-TraceId");
        long beginTime = System.currentTimeMillis();
        startTimeThreadLocal.set(beginTime);
        log.info(LOG_INTERVAL_S_JSON_FORMAT, request.getRequestURI(), new SimpleDateFormat("hh:mm:ss.SSS").format(beginTime));
    }

    private void end(HttpServletRequest request){
        Long beginTime = startTimeThreadLocal.get();
        if(beginTime == null){
            beginTime = System.currentTimeMillis();
        }
        long endTime = System.currentTimeMillis();
        log.info(LOG_INTERVAL_E_JSON_FORMAT, request.getRequestURI(), new SimpleDateFormat("hh:mm:ss.SSS").format(endTime), endTime-beginTime);
    }

    private void returnJson(HttpServletResponse response, String json){
        log.info("<<< {}", json);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            log.error("ScheduledInterceptor response error:",e);
        } finally {
            if (writer != null){
                writer.close();
            }
        }
    }
}
